#include "core/syscall.h"
#include "core/task.h"
#include "applib/applib.h"
#include "tools/log.h"
#include "fs/fs.h"
#include "core/memory.h"
void sys_printmsg(const char* msg,int arg)
{
	print_log(msg,arg);
}

//函数指针
typedef int (*syscall_handler_t)(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint32_t arg3);

// 所有包装函数自动生成
SYSCALL_WRAP_VOID1(sleep, uint32_t)
SYSCALL_WRAP0(getpid)
SYSCALL_WRAP_VOID2(printmsg, const char*, int)
SYSCALL_WRAP0(fork)
SYSCALL_WRAP3(execve, char*, char**, char**)
SYSCALL_WRAP0(sched_yield)
SYSCALL_WRAP2(open, const char*, int)
SYSCALL_WRAP3(read, int, char*, int)
SYSCALL_WRAP3(write, int, char*, int)
SYSCALL_WRAP1(close, int)
SYSCALL_WRAP3(lseek, int, int, int)
SYSCALL_WRAP1(isatty,int)
SYSCALL_WRAP2(fstat, int, struct stat*)
SYSCALL_WRAP1(dup,int)
SYSCALL_WRAP_VOID1(exit,int)
SYSCALL_WRAP_SBRK(sbrk, int)          // 特殊处理
SYSCALL_WRAP1(wait, int*)
SYSCALL_WRAP2(opendir, const char*, DIR*)
SYSCALL_WRAP2(readdir, DIR*, struct dirent*)
SYSCALL_WRAP1(closedir, DIR*)
SYSCALL_WRAP4(ioctl, int, int, int, int)
SYSCALL_WRAP1(unlink, const char*)


static const syscall_handler_t  sys_table[] = {
    [SYS_sleep] = sys_sleep_wrapper,
	[SYS_getpid] = sys_getpid_wrapper,
	[SYS_printmsg] = sys_printmsg_wrapper,
	[SYS_fork] = sys_fork_wrapper,
	[SYS_execve] = sys_execve_wrapper,
	[SYS_yield] =  sys_sched_yield_wrapper,
	[SYS_open] = sys_open_wrapper,
	[SYS_read] = sys_read_wrapper,
	[SYS_write] = sys_write_wrapper,
	[SYS_close] = sys_close_wrapper,
	[SYS_lseek] = sys_lseek_wrapper,
	[SYS_isatty] = sys_isatty_wrapper,
	[SYS_sbrk] = sys_sbrk_wrapper,
	[SYS_fstat] = sys_fstat_wrapper,
	[SYS_dup] = sys_dup_wrapper,
	[SYS_exit] = sys_exit_wrapper,
	[SYS_wait] = sys_wait_wrapper,

	[SYS_opendir] = sys_opendir_wrapper,
	[SYS_readdir] = sys_readdir_wrapper,
	[SYS_closedir] = sys_closedir_wrapper,
	[SYS_ioctl] = sys_ioctl_wrapper,

	[SYS_unlink] = sys_unlink_wrapper,
};

void  do_handler_syscall(syscall_frame_t* frame)
{
     if (frame->func_id < sizeof(sys_table) / sizeof(sys_table[0])) 
	 {
		// 查表取得处理函数，然后调用处理
		syscall_handler_t handler = sys_table[frame->func_id];
		if (handler) 
		{
			int ret = handler(frame->arg0, frame->arg1, frame->arg2, frame->arg3);
            frame->eax = ret;
			return;
		}
	}
	// 不支持的系统调用，打印出错信息
	task_t * task = cur_task();
	print_log("task: %s, Unknown syscall: %d", task->name,  frame->func_id);
}

